import * as THREE from "three";
import camera from "../camera";

export default class AlarmSprite {
  constructor(type = "火警", position = { x: -1.8, z: 3 }, color = 0xffffff) {
    const typeObj = {
      火警: "./textures/tag/fire.png",
      治安: "./textures/tag/jingcha.png",
      电力: "./textures/tag/e.png",
    };
    const map = new THREE.TextureLoader().load(typeObj[type]);
    const material = new THREE.SpriteMaterial({
      map: map,
      color: color,
      blending: THREE.AdditiveBlending,
      transparent: true,
      depthTest: false,
    });

    this.mesh = new THREE.Sprite(material);

    this.mesh.position.set(position.x, 3.5, position.z);
    // 2.我们去声明一个数组属性，用来装传进来的函数，点一次传进来一个，这样的作用是如果点击一次你有多个事件回调我都可以依次执行
    this.fns = [];
    // 4.创建射线
    this.raycaster = new THREE.Raycaster();
    this.mouse = new THREE.Vector2();
    // 3.事件的监听
    window.addEventListener("click", (event) => {
      // 5.获得鼠标点击的世界坐标
      this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      this.mouse.y = -((event.clientY / window.innerHeight) * 2 - 1);
      // 6.设置射线从鼠标点击位置到摄像机射出去
      this.raycaster.setFromCamera(this.mouse, camera);
      // 8.获取参数
      event.mesh = this.mesh;
      event.alarm = this;
      // 7.重点：有个方法可以直接拿到想要的物体进数组
      const intersects = this.raycaster.intersectObject(this.mesh);
      // 7.1只有当有长度说明点击到了，才执行点击函数
      if (intersects.length > 0) {
        this.fns.forEach((fn) => {
          fn(event);
        });
      }
    });
  }
  // 1.声明方法，但是这里不忙着拿到传进来的逻辑开始调用这个函数，因为现在还没有事件监听
  onClick(fn) {
    this.fns.push(fn);
  }
  remove() {
    this.mesh.remove();
    this.mesh.removeFromParent();
    this.mesh.geometry.dispose();
    this.mesh.material.dispose();
  }
}
